package com.health.system.springSecurity;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.health.system.javacommon.util.JsonUtil;
import com.health.system.model.organiza.DataOrganizations;
import com.health.system.model.system.Permission;
import com.health.system.model.system.Role;
import com.health.system.model.system.User;
import com.health.system.service.organiza.DataOrganizationsManager;
import com.health.system.service.system.PermissionManager;
import com.health.system.service.system.UserManager;

/**
 * <p>title:查询用户和用户对应的权限</p>
 * <p>title:用户登录验证及取出用户所拥有的权限</p>
 * <p>Description:实现SpringSecurity的UserDetailsService接口,获取用户Detail信息.</p>
 * <p>Description:认证用户实现UserDetailsService类</p>
 * <p> 封装登录操作员的相关信息</p>
 * @author pch 2010.5.20 
 * 
 */
@Transactional(readOnly = true)
public class UserDetailServiceImpl implements UserDetailsService {
	
	/**操作员管理接口类*/
	private UserManager userManager;
	/**权限管理接口类*/
	private PermissionManager permissionManager;
	/**组织机构接口类*/
	private DataOrganizationsManager dataOrganizationsManager;
	
	
	public void setDataOrganizationsManager(
			DataOrganizationsManager dataOrganizationsManager) {
		this.dataOrganizationsManager = dataOrganizationsManager;
	}

	/**
	 * 实现UserDetailsService的loadUserByUsername接口
	 * @param userName 登录用户名
	 */
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		/**
		 * 取得用户现有菜单
		 * */
		String menus = MyInvocationSecurityMetadataSource.menus;
		if(null==userManager){
			System.out.println("com.health.system.springSecurity.UserDetailServiceImpl userManager is null");
		}
		//SI+USER

		User user = userManager.getUserByName(userName);
		//TOTO 判断用户存在，如果不存在，则抛出异常。 
		if (user == null)
			throw new UsernameNotFoundException("登陆用户名不存在:" + userName + "请重输!!");
		GrantedAuthority[] grantedAuths = obtainGrantedAuthorities(user);

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		int blocked = user.getBlocked();
		boolean accountNonLocked =  true ;
		UserInfo userDetail = new UserInfo(user.getName(), user.getPassword(),
				enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);

		// 菜单部分begin
		List<Permission> list = permissionManager.getAllByType("0");
		if (list != null) {
			for (Permission permission : list) {
				
				String per = permission.getName();
				boolean flag = false;
				label: for (int i = 0; i < grantedAuths.length; i++) {
					if (per.equals(grantedAuths[i].toString())) {
						flag = true;
						break label;
					}
				}
				if (!flag) {
					String value = JsonUtil.endValid(menus, permission
							.getResource());
					if (menus != null) {
						if (value != null) {
							menus = value;
						}
					} else {
						menus = value;
					}
				}
			}
		}

		userDetail.setUserMenuInfo(menus);
		// 菜单部分end
		// 用户登录人基本信息
		userDetail.setUserId(user.getId());
 		userDetail.setUserName(user.getName());
 		userDetail.setUserRealname(user.getRealname());
 		String cpId = user.getCompany();
 		/**设置操作员的机构ID*/
 		userDetail.setCpId(cpId);
		// 用户cpId,公司简称
// 		DataOrganizations cp = dataOrganizationsManager.getById(cpId);
// 		if (null != cp) {
//
// 			userDetail.setCpCode(cp.getCpCode());
// 			userDetail.setComName(cp.getCpName());
// 			userDetail.setAbbreviation(cp.getAbbreviation());
// 			userDetail.setUserNature(cp.getCpNature());
// 		}
		// 用户角色
		List listRole = userManager.getRoleRoleNameByUserName(userName);
		if (null != listRole) {
			StringBuffer role = new StringBuffer();
			StringBuffer roleName = new StringBuffer();
			for (int i = 0; i < listRole.size(); i++) {
				Role roleObject = (Role) listRole.get(i);
				if (i > 0 && i < listRole.size()) {
					role.append(",");
					roleName.append(",");
				}
				role.append(roleObject.getName());
				roleName.append(roleObject.getDescription());
			}
			userDetail.setRole(role.toString());
			userDetail.setRoleName(roleName.toString());
		}

		return userDetail;
	}

	private GrantedAuthority[] obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		List<Permission> permissionList = permissionManager
				.getPermissionByUserId(user.getId());
		if (permissionList != null) {
			for (Permission permission : permissionList) {
				String name = permission.getName();
				if (name != null) {
					authSet.add(new GrantedAuthorityImpl(name));
				}
			}
		}
		return authSet.toArray(new GrantedAuthority[authSet.size()]);
	}

	public void setPermissionManager(PermissionManager permissionManager) {
		this.permissionManager = permissionManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}



}